package com.fowo.api.walmart.util;

import cn.hutool.core.lang.Assert;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fowo.api.datainterface.aspect.BaseAspect;
import com.fowo.api.datainterface.constants.DataTypeKind;
import org.apache.commons.codec.binary.Base64;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class WalmartUtil {

    private static final String TOKEN_URL = "https://marketplace.walmartapis.com/v3/token";

    public static String getToken(String clientId,String clientSecret){

        String str = clientId+ ":" + clientSecret;
        String base = "Basic " + Base64.encodeBase64String(str.getBytes());
        Map<String,String> headers = new HashMap<>();
        headers.put("Authorization",base);
//        headers.put("WM_SVC.NAME","Walmart Marketplace");
        headers.put("WM_SVC.NAME","Walmart Service Name");
        headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString());
        HttpResponse response = HttpRequest.post(TOKEN_URL)
                .addHeaders(headers)
                .body("grant_type=client_credentials", "application/x-www-form-urlencoded")
                .execute();
        JSONObject jsonObject = JSONUtil.parseObj(response.body());
        Assert.notNull(jsonObject.get("access_token"),"授权信息异常，请检查密钥");
        String token = jsonObject.get("access_token").toString();
        return token;
    }

    public static BaseAspect getBaseAspect() {
        return new BaseAspect(DataTypeKind.WALMART.getValue());
    }
}
